package com.chaodev.base.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.chaodev.base.dao.DepartDao;
import com.chaodev.base.dto.DepartDTO;
import com.chaodev.base.model.Depart;
import com.chaodev.base.service.IDepartService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class DepartServiceImpl implements IDepartService {

    @Autowired
    private DepartDao departDao;

    @Override
    public List<Map<String, Object>> getDepartTree(Map<String, Object> map) {
        return departDao.getDepartTree(map);
    }

    @Override
    public List<Map<String, Object>> getDepartAndUserTree(Map<String, Object> map) {
        return departDao.getDepartAndUserTree(map);
    }


    @Override
    public PageInfo<DepartDTO> departQuery(Map<String, Object> map) {
        int page = Integer.parseInt(map.get("P_PAGE").toString());
        int pageSize = Integer.parseInt(map.get("P_PAGESIZE").toString());
        PageHelper.startPage(page, pageSize);
        List<DepartDTO> departDTOS = departDao.departQuery(map);
        return new PageInfo<>(departDTOS, pageSize);
    }

    @Override
    public Depart getDepartAddLevelAndParentIds(Depart depart) {
        return departDao.getDepartAddLevelAndParentIds(depart);
    }

    @Override
    public boolean departAddOracle(Depart depart) {
        int result = departDao.departAddOracle(depart);
        return result != 0;
    }

    @Override
    public boolean departAddMysql(Depart depart) {
        String maxIdByPId = departDao.findMaxIdByPId(depart.getParentDepartId());
        if(!StrUtil.isEmpty(maxIdByPId)) {
            String pevId = StrUtil.sub(maxIdByPId, 0, StrUtil.length(maxIdByPId) - 3);
            String endId = StrUtil.sub(maxIdByPId, StrUtil.length(maxIdByPId) - 3, StrUtil.length(maxIdByPId));
            int afterId = Integer.parseInt(endId);
            afterId = afterId + 1;
            String lastId = StringUtils.leftPad(String.valueOf(afterId), 3, "0");
            depart.setDepartId(pevId + lastId);
        }else{
            depart.setDepartId(depart.getParentDepartId() + "01");
        }
        int result = departDao.departAddMysql(depart);
        return result != 0;
    }

    @Override
    public boolean departUpd(Depart depart) {
        int result = departDao.departUpd(depart);
        return result != 0;
    }

    @Override
    public boolean departDelete(Depart depart) {
        int result = departDao.departDelete(depart);
        return result != 0;
    }

    @Override
    public List<DepartDTO> getMenuZtree(Map<String, Object> map) {
        return departDao.getMenuZtree(map);
    }

    @Override
    public List<Depart> getDepartList(String id) {
        return departDao.getDepartList(id);
    }
}
